<template>
  <div>
    <span class="follow-label fl">{{$t("webchat.relationBusiness")}}:</span>
    <div>
      <ul>
        <li class="follow-agent follow-common1" v-for="item in relatedBusiness" :key="item" @click.stop="relationBusinessDetail(item)">{{item}} 
            <i class="el-icon-close" @click.stop="closeRelatedBusiness(item)" v-show="masterSelect"></i>
        </li>
      </ul>
      <el-popover placement="top" width="230" ref="relationPopover" v-model="relatePopoverShow" trigger="click" @show="popoverShow">
        <div class="relationWrap" style="text-align: right; margin: 0">
          <el-input
            :placeholder="$t('business.businessTip')"
            v-model="searchContent"
            size="mini"
            @keyup.native.enter="handleIconClick"
          >
            <i
              class="el-input__icon el-icon-search"
              slot="suffix"
              @click="handleIconClick"
            >
            </i>
          </el-input>
          <ul style="margin-top: 10px">
            <li
              v-for="(i, idx) in relatedBusinessListNew"
              :key="idx"
              class="relationLi"
              :class="{ active: isActive }"
              @click="relationChange(i)"
            >
              <div style="padding: 8px 5px 7px 0">
                <div class="one">
                  <p class="font14 card-step">
                    <span class="card-step-item">{{
                      i.businessType.name
                    }}</span>
                    <span style="padding: 0 5px"> - </span>
                    <span class="card-step-item" :class="i.businessStep.type">{{
                      i.businessStep.name
                    }}</span>
                  </p>
                  <p class="font12 card-time">
                    {{ i.createTime }}
                  </p>
                </div>
                <div class="two">
                  <div class="card-left">
                    <i
                      :class="{
                        ['icon-chaoshi__' + $i18n.locale]: i.processTimeout,
                      }"
                      class="iconfont process-timeout"
                    ></i>
                    <i class="iconfont icon-yiguanzhu" :class="i.follow"></i>
                  </div>
                  <div class="card-right">
                    <div class="card-customer">
                      <div
                        :class="[i.userName.className]"
                        class="fl customer-name"
                      >
                        {{ i.userName.name }}
                      </div>
                      <div class="creator-master">
                        <span class="name fl">{{ i.agentBefore }}</span>
                        <span class="iconfont icon-dailingqu fl"></span>
                        <span class="name fl">{{ i.agentAfter }}</span>
                      </div>
                    </div>
                    <div
                      class="summary"
                      style="display: -webkit-box; -webkit-box-orient: vertical"
                    >
                      {{ i.businessType.summary.join(" | ") }}
                    </div>
                  </div>
                </div>
              </div>
              <div v-show="isActive" class="relationDuihao">
                <i class="el-icon-check" style="color: #fff"></i>
              </div>
            </li>
          </ul>
          <el-button
            type="primary"
            size="mini"
            style="margin-top: 10px"
            @click="saveRelatedBusiness"
            >{{ $t("public.save") }}</el-button
          >
        </div>
      </el-popover>
      <div class="follow-agent-wrap">
        <span
          class="follow-agent-add follow-common"
          v-popover:relationPopover
          @click="addRelationBusiness"
          v-if="masterSelect"
          ><i class="el-icon-plus"></i> {{ $t("public.add") }}</span
        >
      </div>
    </div>
    <el-dialog
      :visible.sync="relatedBusinessIsShow"
      width="1000px"
      @close="detailClose"
      :title="$t('business.businessHistoryDetail')"
      append-to-body
    >
      <div class="detailWrap">
        <business class="business-dialog" :busId="busId" :showHistory="true" v-if="relatedBusinessIsShow" :typeObj="typeObj" v-on:event="businessEvent" :callScreen="true" :relatedBusinessShow="false"></business>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {timeFormat} from '@/utils/m7Utils.js'
import {getStartStep,sortBusinessFields} from '@/utils/workflowUtils.js'
export default {
    name:'relatedBusiness',
    props:{ 
      relatedBusiness: {
        type: Array,
        default:[]
      },//已关联工单
      relatedBusinessShow: {type: Boolean, default: true},//详情中不能再点击详情
      masterSelect:{type:Boolean, default: true},//是否有权限操作关联工单
    },
    data(){
        return{
          relatedBusinessIsShow:false,//工单详情弹窗
          businessDetail:{},//工单详情
          isActive:false,//动态class
          searchContent:'',//搜索工单input框
          relatedBusinessList:[],//工单搜索数据
          relatedBusinessListNew:[],//搜索工单展示数据
          showHistory:true,//工单历史详情是否展示
          busId:'',//工单id
          relatePopoverShow: false
        }
    },
    computed: {
      typeObj () {
        let rou = this.$route.path.split('/')
        return {
          type: rou[2],
          tabType: rou[3]
        }
      },
    },
    watch: {
      //工单搜索数据整理成展示数据
      relatedBusinessList: {
        deep: true,
        handler: function () {
          let hh = this.relatedBusinessList || []
          this.relatedBusinessListNew = []
          for (let i = 0; i < hh.length; i++) {
            let item = hh[i]
            let one = {}
            one.userName = this.name(item)
            one.businessType = this.businessType(item)
            one.agentAfter = this.agentAfter(item.master)
            one.agentBefore = this.agentBefore(item.createUser)
            one.businessStep = this.businessStep(item.flow, item.status, item.step)
            one.createTime = timeFormat(item.createTime, 'card')
            one._id = item._id
            one.customer = item.customer
            one.processTimeout = item.processTimeout
            one.priority = item.priority
            one.follow = 'none'
            one.stepId = item.step
            one.noRead = item.isReadFlag === false
            // 稍后处理
            one.laterProcess = this.tabType === 'business_my' && item.laterProcess
            if (item.followedAgents && item.followedAgents.indexOf(this.sessionId) !== -1) {
              one.follow = ''
            }
            this.relatedBusinessListNew.push(one)
          }
        }
      },
    },
    components: {
      Business: () => import('./index.vue'),
      History: () => import('./History.vue')
      
    },
    methods:{
         //添加关联工单
      addRelationBusiness(){
      },
      popoverShow(){
        this.relatePopoverShow = true
      },
      //保存关联工单
      saveRelatedBusiness(){
        if(this.isActive&&this.searchContent){
          this.$emit('saveRelatedBusiness',this.searchContent)
          this.searchContent = ''
          this.relatedBusinessListNew = []
          this.relatePopoverShow = false
        }else{
          this.$message.error(this.$t('business.selectBusiness'))
        }
      },
      //工单列表点击更改class
      relationChange(){
        this.isActive = !this.isActive
      },
      //关联工单详情
      relationBusinessDetail(number){
        if(this.relatedBusinessShow){
          this.$store.dispatch('getBusinessDetailById', {number}).then((res) => {
            if (res) {
              this.businessDetail = res
            }else{
              this.businessDetail = {}
            }
            //当工单详情为空时不打开弹窗
            if(this.businessDetail&&Object.keys(this.businessDetail).length >0){
              this.busId = this.businessDetail._id
              this.relatedBusinessIsShow = true
            }
          })
        }
      },
      //关闭弹窗
      detailClose(){
        this.relatedBusinessIsShow = false
      },
      //删除关联工单
      closeRelatedBusiness(number){
        this.$emit('closeRelatedBusiness',number)
      },
      //搜索
      handleIconClick(){
        this.isActive = false
        if(!this.searchContent){
          this.relatedBusinessList = []
        }else{
          let data = {number:this.searchContent}
          this.$store.dispatch('queryAllBusiness', data).then((res) => {
            if (res && res.success) {
              if (res.list.length === 0) {
                this.relatedBusinessList = []
              }else{
                this.relatedBusinessList = res.list
              }
            }
          })
        }
      },
      businessEvent (data) {
        if (data.event === 'backAction') {
          this.backShow = false
        } else if (data.event === 'stepAction') {
          this.approvalshow = false
        } else if (data.event === 'commentAction') {
          let info = data.data || {}
          let form = info.form
          if(info.form.attach&&info.form.attach.length>0){
            info.form.existAttach = true
          }else{
            info.form.existAttach = false
          }
          if (info.isService && info.action === 'out') {
            if (!form.backInfo) {
              this.$message.error(this.$t('business.replyRequire'))
              return
            }
            form = Object.assign({history_type: 'reply'}, form)
            this.$store.dispatch('addConfigBusinessBackInfo', form).then(() => {
              let data = {
                'businessId': this.detail._id,
                'step': this.detail.step,
                'action': 'configBusiness',
                'history_type': 'reply',
                'excuteData': {
                  'backInfo': form.backInfo,
                  'attach': form.attach || []
                },
                'time': getCurrentDateTime(),
                'master': this.$store.state.session.user._id
              }
              this.$refs.businessComment.cancel()
              this.$store.commit(types.ADD_BUSINESS_ACTION_HISTORY, {data})
              // 备注成功后清楚缓存
              let busCache = this.$getCache('busCache')
              if (busCache[this.detail._id + 'commentOut']) {
                delete busCache[this.detail._id + 'commentOut']
              }
            })
          } else {
            if (!form.backInfo) {
              this.$message.error(this.$t('business.commentRequire'))
              return
            }
            this.$store.dispatch('addBusinessBackInfo', form).then(() => {
              let data = {
                'businessId': this.detail._id,
                'step': this.detail.step,
                'action': 'comment',
                'excuteData': {
                  'backInfo': form.backInfo,
                  'attach': form.attach || []
                },
                'time': getCurrentDateTime(),
                'master': this.$store.state.session.user._id
              }
              this.$refs.businessComment.cancel()
              this.$store.commit(types.ADD_BUSINESS_ACTION_HISTORY, {data})
              // 备注成功后清楚缓存
              let busCache = this.$getCache('busCache')
              if (busCache[this.detail._id + 'commentIn']) {
                delete busCache[this.detail._id + 'commentIn']
              }
            })
          }
        }
        this.$emit('event', data)
      },
      businessType (item) {
        let businessFlows = this.$getCache('businessFlow') || []
        for (let i = 0; i < businessFlows.length; i++) {
          if (businessFlows[i]._id === item.flow) {
            let {name, showFields, fields} = businessFlows[i]
            let step = getStartStep(businessFlows[i])
            let stepFields = step.stepFields || []
            let detail = [{name: this.$t('business.businessNumber'), value: item.number}]
            let summary = []
            sortBusinessFields(stepFields, fields, item, detail, 'card')
            if (showFields && showFields.length) {
              detail.forEach((item) => {
                if (showFields.indexOf(item._id) !== -1 && item.value) {
                  summary.push(item.value)
                }
              })
            }
            return {name, detail, summary}
          }
        }
        try {
          const data = {
            env: {
              browser: {name: 'Chrome', version: '67.0.3396.99'},
              os: 'Mac',
              userAgent: 'Mozilla/5.0'
            },
            extra: {
              componentName: '工单卡片'
            },
            errorType: 'TypeError',
            message: '工单卡片',
            referrer: 'http://kf.com/customer',
            stacktrace: {
              frames: []
            },
            trimHeadFrames: 1,
            url: '',
            exception: {
              values: [{
                type: 'TypeError',
                value: '错误信息：工单卡片信息item.flow：' +
                (item.flow || '') +
                '   item.number：' + item.number + '工单类型flows长度：' + businessFlows.length,
                stacktrace: {
                  frames: []
                }
              }]
            }
          }
          let req = {
            data,
            action: 'app.collect.collectVueErrorInfo'
          }
          http.fetch(req, 'post')
            .then((res) => {
            })
            .catch(err => {
              console.error(err)
            })
        } catch (err) {
          console.log(err)
        }

        return {name: '', detail: [], summary: []}
      },
      businessStep (flowId, status, step) {
        let businessStep = {name: '', type: ''}
        let businessFlows = this.$getCache('businessFlow')
        if (!businessFlows) {
          return businessStep
        }
        let flow = null
        for (let i = 0; i < businessFlows.length; i++) {
          if (businessFlows[i]._id === flowId) {
            flow = businessFlows[i]
            break
          }
        }
        if (status !== 'complete' && status !== 'cancel') {
          businessStep.type = 'b-step'
        } else {
          businessStep.type = 'finish'
        }
        let steps = flow ? flow.steps : []
        for (let i = 0; i < steps.length; i++) {
          var stepsItem = steps[i]
          if (stepsItem._id === step) {
            businessStep.name = stepsItem.name
            break
          }
        }
        return businessStep
      },
      agentAfter (master) {
        if (master === '') {
          return ''
        } else {
          let agent = this.$agentsMap() || {}
          return agent[master] ? agent[master].displayName : ''
        }
      },
      agentBefore (createUser) {
        let agent = this.$agentsMap() || {}
        return agent[createUser] ? agent[createUser].displayName : ''
      },
      name (item) {
        let name = ''
        let className = ''
        if (!item.customer) {
          name = this.$t('customer.customerSlot.unlocation')
          className = 'unknowCus'
        } else if (!item.name) {
          name = this.$t('business.hasRemoveCus')
          className = 'deleteCus'
        } else {
          name = item.name
        }
        return {className, name}
      },
    },
};
</script>

<style lang='stylus' scope>
    @import '../../../../assets/common.styl'
    .follow-label
      line-height 24px
      font-size 12px
    .follow-agent-wrap
      padding-left 72px
      .follow-common
        float left
        position relative
        line-height 24px
        margin 0 0 10px 10px
        padding 0 10px
        border-radius 4px
        font-size 12px
      .follow-agent-add
        border 1px solid $c-main
        color $c-main
        cursor pointer
      .follow-agent
        line-height 26px
        background-color $c-bus-label
        color #fff
        &:hover
          .el-icon-close
            display block
        .el-icon-close
          display none
          position absolute
          right -10px
          top -10px
          width 24px
          height 24px
          font-size 16px
          line-height 24px
          transform scale(0.6)
          text-align center
          color #fff
          background-color $c-pink
          border-radius 50%
          border 1px solid #fff
          cursor pointer
    .detail-table-wrap
      position fixed
      top 0
      left 0
      right 0
      bottom 0
      background rgba(0,0,0,.5)
      z-index 200
    .approval
      padding-top 20px
    .text 
      color #000
      cursor pointer
      font-size 12px
.relationWrap
  .active 
    position relative
    padding 8px
    border 2px solid #459AE9
  .relationLi
    position relative
    padding 8px
    .relationDuihao
      position:absolute
      height:16px
      width:16px
      top:-1px
      right:-1px
      background rgb(69, 154, 233)
    .one
      height 18px
      display: flex
      flex-direction row
      justify-content space-between
      .card-step
        color $cf-gray2
        font-weight bold
        text-align left
        overflow hidden
        display flex
      .card-time
        color: $cf-gray6
        flex-shrink 0
        flex-grow 1
        text-align right
        margin-left 10px
        .icon-shaohouchuli
          display inline-block
          color $c-main
        .icon-shaohouchuli1
          color $c-pink !important
          display inline-block
        .icon-shaohouchuli2
          color #E6A23C !important
          display inline-block
        .icon-shaohouchuli3
          color $c-main !important
          display inline-block
        .icon-shaohouchuli4
          color #58970f !important
          display inline-block
      .card-step-item
        /*max-width 97px*/
        display inline-block
        text-overflow ellipsis
        overflow hidden
        white-space nowrap
      .b-step
        color $c-bus-step
      .finish
        color $cf-gray5
    .two
      display flex
      flex-direction row
      line-height 20px
      font-size 12px
      color $cf-gray4
    .card-left
      width: 24px
      min-width 24px
      text-align left
      i
        font-size 16px
        display block
      .process-timeout
        line-height 20px
        color: $c-pink
      .icon-yiguanzhu
        line-height 18px
        color $c-main
    .card-right
      display flex
      flex-direction column
      line-height 20px
      width calc(100% - 24px)
      flex-grow 1
      .card-customer
        display flex
        flex-direction row
        justify-content space-between
        .customer-name
          color $cf-gray2
          text-overflow ellipsis
          overflow hidden
          white-space nowrap
          flex-grow 1
          padding-right 10px
          text-align left
        .creator-master
          display flex
      .deleteCus
        text-decoration line-through
      .icon-dailingqu
        margin 0 5px
      .summary
        padding-top 1px
        display -webkit-box
        -webkit-line-clamp: 2;
        overflow: hidden;
        white-space normal
        line-height 18px
      .name
        max-width 52px
        text-overflow ellipsis
        overflow hidden
        white-space nowrap
      .tasktome
        margin-top 1px
        padding 1px 6px
        border 1px solid $c-main
        border-radius 4px
        line-height 14px
        max-width 45px
        height 18px
        box-sizing border-box
        color $c-main
        font-size 12px
        &:hover
          background: $c-main;
          border-color: $c-main;
          color: #fff;
.follow-common1
  float left
  position relative
  line-height 24px
  margin 0px 5px 5px 5px
  padding 0 10px
  border-radius 4px    
  background-color #91c1f1
  color #fff
  font-size 12px
  cursor pointer
.follow-agent-add
  cursor pointer
.el-icon-close
  font-size 12px
.follow-agent
  &:hover
    .el-icon-close
      display block
  .el-icon-close
    display none
    position absolute
    right -10px
    top -10px
    width 24px
    height 24px
    font-size 12px
    line-height 24px
    transform scale(0.6)
    text-align center
    border-radius 50%
    background $c-pink
    color #fff
    cursor pointer
.detailWrap
  margin-top 15px
  max-height 800px
  overflow-y auto
</style>
